#include "widget.h"
#include "ui_widget.h"
#include <QUrlQuery>
#include <QJsonDocument>
#include <QClipboard>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished,
            this, &Widget::handle_reply);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    QUrl url("https://aip.baidubce.com/oauth/2.0/token");

    QUrlQuery query;
    query.addQueryItem("grant_type", "client_credentials");
    query.addQueryItem("client_id", ui->akEdit->text());
    query.addQueryItem("client_secret", ui->skEdit->text());

    url.setQuery(query);

    QNetworkRequest request(url);

    client->get(request);
}

void Widget::handle_reply(QNetworkReply *reply)
{
    QJsonDocument json = QJsonDocument::fromJson(reply->readAll());
    ui->tokenEdit->setText(json["access_token"].toString());
    QGuiApplication::clipboard()->setText(json["access_token"].toString());
    reply->deleteLater();
}

